/**
 * Created by Class on 2016/4/22.
 */
var _userList = {
    C: "TM-12345-test1111111222",
    B: "TM-1234-test1111111222",
    A: "TM-17219-fd52d846faae416bb1d811c7fb709136"
};

var CALL_RSP_OK = 1;
var CALL_IN = 2;

var  FAILED = 0;
var  FAILED_DOUBLE=-1;
var  SUCCESS = 1;
var  CONNECTLOST = 2;
var  BE_KICK_OFF = 3;
var  CONNECT_1014 = 1014;
export function registA() {
    var me = {
        user_name: '测试A',
        user_id: 123,
        token: _userList.A,
        mqtt_server: 'msg.ehomecare.vip'
    };
    regist(me);
    return;
}

function onConnect(status) {
    if(status == SUCCESS ){
        alert("注册成功！");
    }
    else if(status == CONNECTLOST ){
        console.log("onConnectionLost:" + e.errorCode + "\n");
    }
    else if(status == CONNECT_1014 ){
        isDisconnect = 0;
    }
}

var webStatus = 0; //签入状态 0:未签入 1:示闲 2:示忙
var isOpenInterval = false;
var interval = null;
var isRuncall = null;

function videoCallback(x_peerInfo, msg) {
    var peerInfo = {};
    peerInfo.token = x_peerInfo.topic_tome;
    peerInfo.user_id = x_peerInfo.friend_id;

    if (msg.type == "offer") {
        console.log("offer : " + msg);
        if (webStatus == 2) {
            RTCVideo.callBusy(peerInfo.token);
            return;
        }
        console.log("call token" + peerInfo.token);

        if (RTCVideo.getGroupId() != null) {
            if (RTCVideo.getGroupId() == msg.groupId) {
                //第三方接入

                try {
                    var remotevideoC = document.getElementById("remoteC");
                    RTCVideo.acceptAttendant(remotevideoC, peerInfo, msg);
                } catch (e) {
                    console.log("error msg is " + e.message);
                }

            } else {
                RTCVideo.callBusy(peerInfo.token);
            }
            return;
        } else {
            //自动接听
            try {
                var myvideo = document.getElementById("local");
                var remotevideo = document.getElementById("remote");
                var remotevideoC = document.getElementById("remoteC");
                var remoteVideoList = new Array();
                remoteVideoList.push(remotevideo);
                remoteVideoList.push(remotevideoC);


                RTCVideo.accept(myvideo, remoteVideoList, peerInfo, msg)
            } catch (e) {
                console.log("error msg is " + e.message);
            }
            //响铃
            // $("#bg_music").attr("src","/images/new/c.mp3");
        }
    } else if (msg.type == "answer") {} else if (msg.type == "iceconnected") {
        console.log("iceconnected");
        callOutLoopPlayer.stopPlay();
    } else if (msg.type == "busy") {
        alert("用户繁忙！");
    } else if (msg.type == "bye"){
        
    callOutLoopPlayer.stopPlay();
    }
}
//处理循环播放的辅助类
var LoopPlayer =function (audioPath, interval) {
    var audioObject;
    var ringTimer;

    var playAudio = function () {
        audioObject = new Audio(audioPath);
        audioObject.play();
    };

    var startPlay = function () {
        stopPlay();
        playAudio();
        ringTimer = setInterval(playAudio, 4000);
    };

    var stopPlay = function () {
        if (ringTimer) {
            clearInterval(ringTimer);
            ringTimer = undefined;
        }
        if (audioObject) {
            audioObject.pause();
            audioObject = undefined;
        }
    };

    this.startPlay = startPlay;
    this.stopPlay = stopPlay;
};

var callInAudioPath = "/images/new/c.mp3";
var callOutAudioPath = "/test/dududu.mp3";
var callInLoopPlayer = new LoopPlayer(callInAudioPath,5000);
var callOutLoopPlayer = new LoopPlayer(callOutAudioPath,4000);

export function registB() {
    var me = {
        user_name: '测试B',
        token: _userList.B,
        user_id: 1234,
        mqtt_server: 'msg.ehomecare.vip'
    };
    regist(me);
    return;
}

function registC() {
    var me = {
        user_name: '测试C',
        token: _userList.C,
        user_id: 12345,
        mqtt_server: 'msg.ehomecare.vip'
    };
    regist(me);
    return;
}

function regist(user) {
    RTCVideo.registMessageListener(onMessage);
    RTCVideo.registConnectListener(onConnect);
    RTCVideo.registVideoEventListener(videoCallback);
    RTCVideo.regist(user);
    RTCVideo.clearServers();
    RTCVideo.addVideoServer({
        uri: '139.196.75.243'
    });
}

export function sendA(msg) {
    var msgNotification = {
        type: 'mymsg',
        mymsg: msg
    }
    RTCVideo.sendNotification(msgNotification, _userList.A);
}
let peer;

export function callA() {
    initMeeting("test2");
    // var msgNotification = {
    //     type: 'call',
    //     callmsg: {
    //         roomName: 'test2'
    //     }
    // }
    // peer = _userList.A;
    // RTCVideo.sendNotification(msgNotification, _userList.A);
}

export function callA2() {
    let localVideo = document.getElementById("local");
    RTCVideo.initCall(localVideo,false).then(
        () => {
            let remoteVideo = document.getElementById("remote");
            RTCVideo.invite(remoteVideo, {
                user_id: 17219,
                token: _userList.A
            });
        }
    );
    callOutLoopPlayer.startPlay();
}
export function callA3() {

    let localVideo = document.getElementById("local");
    RTCVideo.initCall(localVideo,true).then(
        () => {
            let remoteVideo = document.getElementById("remote");

            RTCVideo.invite(remoteVideo, {
                user_id: 17219,
                token: _userList.A
            });
        }
    );
    // startPlay();
    callOutLoopPlayer.startPlay();
}
var localWs = null;
var remoteWs = null;

export function record() {

    try {
        console.log("enter record");
        localWs = new websocketUploader();
        localWs.setFileName("local" + (new Date()).valueOf() + ".webm");
        localWs.init("wss://local.ehomecare.vip:4433/ws", localMsgCallBack);
        localWs.setStream(RTCVideo.LocalVideo.getInstance().m_LocalStream);
        remoteWs = new websocketUploader();
        remoteWs.setFileName("remote" + (new Date()).valueOf() + ".webm");
        remoteWs.init("wss://local.ehomecare.vip:4433/ws", remoteMsgCallBack);
        var peerList = RTCVideo.LocalVideo.getInstance().getPcAy();

        for (var token in peerList) {
            remoteWs.setStream(peerList[token].m_RemoteStream);
            break;

        }

    } catch (error1) {
        console.log("error---" + error1.message);
    }
}

var localMsgCallBack = function(message) {};

var remoteMsgCallBack = function(message) {};

export function callC2() {

    let remoteVideoC = document.getElementById("remoteC");

    RTCVideo.invite(remoteVideoC, {
        user_id: 12345,
        token: _userList.C
    });
}

export function bye() {
    if (peer) {
        var msgNotification = {
            type: 'bye'
        }
        RTCVideo.sendNotification(msgNotification, peer);
    }
    unload();
    peer = undefined;

}

export function bye2() {
    if (localWs != null) {
        localWs.stopRecord();
        localWs = null;
    }
    if (remoteWs != null) {
        remoteWs.stopRecord();
        remoteWs = null;
    }
    callOutLoopPlayer.stopPlay();
    RTCVideo.hungUp();
}

function onMessage(noti) {
    if (noti.notify_type) {
        if (noti.notify_type == 2001) {
            var sdp = JSON.parse(noti.msg);
            if (sdp.type == "bye" || sdp.type == "busy") {
                //to do
            }
        }
    }
    switch (noti.type) {
        case 'call':
            peer = noti.senderToken;
            // initMeeting(noti.callmsg.roomName);
            break;
        case 'bye':
            // unload();
            break;
        case 'mymsg':
            console.log(noti.mymsg);
            break;
    }
}

var playTimerTask = null;
function startPlay() {
    stop();
    $("#call_music").attr("src", "/test/dududu.mp3");
    playTimerTask = setInterval(function () {
        $("#call_music").attr("src", "/test/dududu.mp3");
    }, 4000);
}

function stop() {
    if (playTimerTask){
        window.clearInterval(playTimerTask);
    }
    $("#call_music").attr("src","");
}